package com.wanghua.mall.order.listener;

import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.rabbitmq.client.Channel;
import com.wanghua.mall.order.config.OrderRabbitMQConfig;
import com.wanghua.mall.order.entity.OrderEntity;
import com.wanghua.mall.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 定时关闭订单
 *
 * @author wanghua
 * @create 2021-09-10 16:17
 */
@Component
@RabbitListener(queues = OrderRabbitMQConfig.ORDER_RELEASE_ORDER_QUEUE_NAME)
public class OrderCloseListener {
    @Resource
    private OrderService orderService;

    /**
     * 关闭订单
     *
     * @param message message
     * @param orderEntity orderEntity
     * @param channel channel
     */
    @RabbitHandler
    public void closeOrder(Message message, OrderEntity orderEntity, Channel channel) throws IOException {
        try {
            // TODO 手动调用支付宝收单 https://opendocs.alipay.com/apis/api_1/alipay.trade.close
            //用于交易创建后，用户在一定时间内未进行支付，可调用该接口直接将未付款的交易进行关闭。
            //https://github.com/alipay/alipay-easysdk/blob/master/APIDoc.md


            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
